// components/music/music.js
import { initMusic } from './core'

let touchStartX = 0;
let touchMoveX = 0;
let touchTime = 0
let oldMove = 0
class TouchTime {
  static core = { flag: null }
  static start(that) {
    if (this.core.flag === null) {
      this.core.flag = setInterval(() => {
        touchTime += 100
        if (touchTime > 350) { //长按
          if (that.data.timeDialogFlag) return
          wx.vibrateShort()
          that.setData({
            timeDialogFlag: true,
          })
        }
      }, 100)
    }
  }
  static end() {
    if (this.core.flag === null) return
    clearInterval(this.core.flag)
    this.core.flag = null
  }
}
class MiuscCurrentTime { //长按继续计时
  static core = { flag: null }
  static start(that) {
    if (this.core.flag === null) {
      this.core.flag = setInterval(() => {
        that.setData({
          moveToTime: parseInt(that.data.music.currentTime)
        })
      }, 200)
    }
  }
  static end() {
    if (this.core.flag === null) return
    clearInterval(this.core.flag)
    this.core.flag = null
  }
}
class ProgressTime {
  core = { flag: null }
  start(that) {
    if (this.core.flag === null) {
      console.log(that.data.status)
      this.core.flag = setInterval(() => {
        that.setData({
          percentage: GetPercent(parseInt(that.data.music.currentTime), parseInt(that.data.music.duration))
        })
      }, 200)
    }
  }
  end() {
    if (this.core.flag === null) return
    clearInterval(this.core.flag)
    this.core.flag = null
  }
}
function GetPercent(num, total) {
  num = parseFloat(num);
  total = parseFloat(total);
  if (isNaN(num) || isNaN(total)) {
    return "-";
  }
  return total <= 0 ? "0%" : (Math.round(num / total * 10000) / 100.00) + "%";
}
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    info: {
      type: Object,
      value: {
        // name: '',
        // author: '',
        // width: 400,
        // height: 100,
        // color: '',
        // border: 0,
        // url: '',
        // flag: false,
        // moveDisable: false,
        // progressDisable: false,
        // longTouchDisable: false,
        // loadOverTime: 30000
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    music: null,
    style: '',
    status: true,
    currentToTime: 0,
    timeDialogFlag: false,
    duration: 0,
    moveToTime: 0,
    percentage: '0%',
    soundbyteArr: [],
    progressTime: null,
    loadFlag: false
  },



  ready() {
    this.data.progressTime = new ProgressTime()

    try {
      if (this.properties.info.url === undefined) {
        throw 'music缺少必填字段url'
      }
    } catch (error) {
      console.error(error)
    }
    if (this.properties.info.name === undefined) {
      this.properties.info.name = ''
    }
    if (this.properties.info.author === undefined) {
      this.properties.info.author = ''
    }
    if (this.properties.info.width === undefined) {
      this.properties.info.width = '100%'
    }
    if (typeof this.properties.info.width === 'number') {
      if (this.properties.info.width < 360) {
        this.properties.info.width = 360 + 'rpx'
      } else {
        this.properties.info.width = this.properties.info.width + 'rpx'
      }
    }
    if (this.properties.info.height === undefined) {
      this.properties.info.height = 100
    }
    if (this.properties.info.color === undefined) {
      this.properties.info.color = "#f00"
    }
    if (this.properties.info.border === undefined) {
      this.properties.info.border = this.properties.info.height / 2
    }
    if (this.properties.info.flag === undefined) {
      this.properties.info.flag = false
    }
    if (this.properties.info.moveDisable === undefined) {
      this.properties.info.moveDisable = false
    }
    if (this.properties.info.progressDisable === undefined) {
      this.properties.info.progressDisable = false
    }
    if (this.properties.info.longTouchDisable === undefined) {
      this.properties.info.longTouchDisable = false
    }
    if (this.properties.info.loadOverTime === undefined) {
      this.properties.info.loadOverTime = 300000
    }

    let info = this.properties.info
    this.setData({
      info
    })
    console.log(info)
    let style
    if (info.name === '') {
      style = `width:${info.width}; height:${info.height}rpx; background-color:${info.color}; border-radius: ${info.border}rpx;`
    } else {
      style = `width:${info.width}; height:${info.height + 50}rpx; background-color:${info.color}; border-radius: ${info.border}rpx;`
    }

    this.setData({
      style
    })
    if (this.properties.info.flag) {
      this.data.music = wx.createInnerAudioContext()
      initMusic(this.data.music, this).setUrl(this.properties.info.url)
    } else {
       this.data.music = wx.createInnerAudioContext()
      initMusic(this.data.music, this)
    }
  },

  detached() {
    this.data.music.stop()
    this.progressEnd()
    this.animationEnd()
    TouchTime.end()
    MiuscCurrentTime.end()
  },
  /**
   * 组件的方法列表
   */
  methods: {
    playerStatus(status) {
      this.triggerEvent('playbackStatus', {
        url: this.data.music.src,
        currentTime: this.data.music.currentTime,
        duration: this.data.music.duration,
        status: status
      });
    },
    progressStar() {
      this.data.progressTime.start(this)
    },
    progressEnd() {
      this.data.progressTime.end(this)
    },
    animationStar() {
      if (this.data.soundbyteArr.length === 0) {
        for (let i = 0; i < 35; i++) {
          let type = Math.floor(Math.random() * (9 - 1 + 1)) + 1
          let width = Math.floor(Math.random() * (5 - 3 + 1)) + 3
          this.data.soundbyteArr.push({
            type: 'soundbyte-animation-' + type,
            stop: '',
            width
          })
        }
      } else {
        for (let i = 0; i < 35; i++) {
          this.data.soundbyteArr[i].stop = ''
        }
      }

      this.setData({
        soundbyteArr: this.data.soundbyteArr
      })
    },
    animationStop() {
      if (this.data.soundbyteArr.length === 0) return
      for (let i = 0; i < 35; i++) {
        this.data.soundbyteArr[i].stop = 'soundbyte-animation-stop'
      }
      this.setData({
        soundbyteArr: this.data.soundbyteArr
      })
    },
    animationEnd() {
      this.data.soundbyteArr = []
      this.setData({
        soundbyteArr: this.data.soundbyteArr
      })
    },
    musicPlayEnd() {
      this.setData({
        percentage: GetPercent(parseInt(this.data.music.duration), parseInt(this.data.music.duration))
      })
    },

    touchstart(e) {
      touchStartX = e.changedTouches[0].clientX

      if (this.properties.info.longTouchDisable) return
      TouchTime.start(this)
      MiuscCurrentTime.start(this)
    },
    touchmove(e) {
      if (this.properties.info.moveDisable) return
      if (Math.abs(touchMoveX) >= 10) {
        MiuscCurrentTime.end()
        if (!this.data.timeDialogFlag) {
          this.setData({
            timeDialogFlag: true,
          })
        }
      }
      touchMoveX = e.changedTouches[0].clientX - touchStartX

      let num
      if (parseInt(this.data.music.currentTime + touchMoveX * this.data.music.fragments) < 0) {
        num = 0
      } else if (parseInt(this.data.music.currentTime + touchMoveX * this.data.music.fragments) > this.data.music.duration) {
        num = parseInt(this.data.music.duration)
      } else {
        num = parseInt(this.data.music.currentTime + touchMoveX * this.data.music.fragments)
      }
      if (oldMove === num) return
      wx.vibrateShort()
      oldMove = num

      this.setData({
        moveToTime: num
      })
    },
    touchend(e) {
      if (Math.abs(touchMoveX) >= 10) {
        this.data.music.seek(this.data.moveToTime)
        if (this.data.progressTime.core.flag === null) {
          this.setData({
            percentage: GetPercent(parseInt(this.data.moveToTime), parseInt(this.data.music.duration))
          })
        }
      }
      this.checkTap()
      TouchTime.end()
      MiuscCurrentTime.end()
      touchMoveX = 0
      touchTime = 0
      this.setData({
        timeDialogFlag: false
      })
      setTimeout(() => {
        this.setData({
          moveToTime: 0
        })
      }, 100)
    },

    checkTap() {
      if (touchTime < 350 && Math.abs(touchMoveX) < 10) {
        this.data.status ? this.data.music.play() : this.data.music.pause()
        if (this.data.music.src !== '') return
        this.data.music.setUrl(this.properties.info.url)
      }
    }
  }
})
